package com.gengzp.common.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

/**
 * @ClassName TraceContextHolder
 * @Description 链路追踪线程上下文变量
 * @Author gengzp
 * @Date 2025/9/24 11:24
 */
public class TraceContextHolder {

    /**
     * 链路追踪id
     */
    private static final ThreadLocal<String> traceId = new TransmittableThreadLocal<>();

    /**
     * 链路日志集合
     */
    private static final ThreadLocal<List<String>> traceLogs = new TransmittableThreadLocal<>();

    /**
     * 当前访问接口url
     */
    private static final ThreadLocal<String> currentControllerUrl = new TransmittableThreadLocal<>();

    public static String getTraceId() {
        return traceId.get();
    }

    public static void setTraceId(String traceId) {
        TraceContextHolder.traceId.set(traceId);
    }

    public static void removeTraceId() {
        traceId.remove();
    }

    public static List<String> getTraceLogs() {
        return traceLogs.get();
    }

    public static void setTraceLogs(List<String> traceLogs) {
        TraceContextHolder.traceLogs.set(traceLogs);
    }

    public static void addTraceLogs(String traceLog) {
        List<String> traceLogs = getTraceLogs();
        if (CollectionUtils.isEmpty(traceLogs)) {
            traceLogs = Lists.newArrayList();
        }
        traceLogs.add(traceLog);
        setTraceLogs(traceLogs);
    }

    public static void removeTraceLogs() {
        traceLogs.remove();
    }

    public static String getCurrentControllerUrl() {
        return currentControllerUrl.get();
    }

    public static void setCurrentControllerUrl(String currentControllerUrl) {
        TraceContextHolder.currentControllerUrl.set(currentControllerUrl);
    }

    public static void removeCurrentControllerUrl() {
        currentControllerUrl.remove();
    }

}
